package entity

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"strconv"
	"strings"
	"time"
)

// 私聊
type P2PMsg struct {
	gorm.Model
	ReceiveId uint      `json:"receive_id"`
	SendId    uint      `json:"send_id"`
	Type      int       `json:"type"` // 0-文字 1-图片 2-语音
	Content   string    `json:"content"`
	IsRead    bool      `json:"is_read"`
	SendTime  time.Time `json:"send_time" gorm:"index"`
	Uuid      string    `json:"uuid"`
}

func (P2PMsg) TableName() string {
	return "p2p_msg"
}

func (p2pmes P2PMsg) String() string {
	return fmt.Sprintf("RecId: %d, SendId:%d, Content:%s, SentTime: %v, UUID: %s", p2pmes.ReceiveId, p2pmes.SendId, p2pmes.Content, p2pmes.SendTime, p2pmes.Uuid)
}

func GetSyncField(sid, tid uint) string {
	return fmt.Sprintf("p2pMsg_%d_%d_exist", sid, tid)
}

func GetMsgZsetKey(sid, tid uint) string {
	return fmt.Sprintf("zset:p2pMsg_%d_%d", sid, tid)
}

func GetSyncSetKey(sid, tid uint) string {
	return fmt.Sprintf("set:p2pMsgSyncStatus_%d_%d", sid, tid)
}

func ExtractSidTidFromZsetKey(zsetKey string) (uint, uint, error) {
	const prefix = "zset:p2pMsg_"
	if !strings.HasPrefix(zsetKey, prefix) {
		return 0, 0, fmt.Errorf("invalid zsetKey format")
	}

	parts := strings.Split(strings.TrimPrefix(zsetKey, prefix), "_")
	if len(parts) != 2 {
		return 0, 0, fmt.Errorf("invalid zsetKey format")
	}

	sid64, err1 := strconv.ParseUint(parts[0], 10, 64)
	tid64, err2 := strconv.ParseUint(parts[1], 10, 64)
	if err1 != nil || err2 != nil {
		return 0, 0, fmt.Errorf("failed to parse sid or tid: %v, %v", err1, err2)
	}

	return uint(sid64), uint(tid64), nil
}
